﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using WebApp.BaseDataSvc;
using System.IO;

namespace WebApp
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class UploadHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Charset = "utf-8";
            string myReturn = string.Empty;
            try
            {
                HttpPostedFile file = context.Request.Files["Filedata"];
                var order = Convert.ToInt32(context.Request.Params["OrderId"]);
                var user = Convert.ToInt32(context.Request.Params["UserId"]);
                if (file != null & user != null)
                {
                    var createTime = DateTime.Now;
                    string dir = WebCommon.GetUploadFileDir(createTime);//文件目录      

                    if (!System.IO.Directory.Exists(dir))
                        System.IO.Directory.CreateDirectory(dir);

                    var localFileName = file.FileName;
                    var fileExt = Path.GetExtension(file.FileName);
                    var saveFileName = createTime.ToString("yyyyMMddHHmmss") + "_" + user.ToString() + fileExt;

                    TB_Attach attach = new TB_Attach();
                    attach.@operator = user;
                    attach.order = order;
                    attach.attachName = file.FileName;//原文件名称
                    attach.ext = Path.GetExtension(file.FileName);
                    attach.size = file.ContentLength;
                    attach.createTime = createTime;

                    /// <summary>
                    /// 数据接口代理
                    /// </summary>
                    BaseDataSvc.BaseDataClient bdProxy = new BaseDataSvc.BaseDataClient();
                    bdProxy.Open();
                    int newAttachId = bdProxy.AddAttach(attach);
                    if (newAttachId > 0)
                    {
                        string filePath = System.IO.Path.Combine(dir, saveFileName);//获取文件的路径,已经保存的文件名
                        file.SaveAs(filePath);
                        myReturn = newAttachId.ToString();
                    }
                    bdProxy.Close();
                }
                else
                    myReturn = "0";
            }
            catch (Exception ex)
            {
                myReturn = ex.Message;
            }
            context.Response.Write(myReturn);//这句代码缺少的话，上传成功后上传队列的显示不会自动消失
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
